package utils;

import java.sql.*;

public class DBHelper {
 private static final String DRIVER="com.mysql.jdbc.Driver";
 private static final String URL="jdbc:mysql://127.0.0.1:3306/login_register?useUnicode=true&characterEncoding=utf8";
 private static final String USER="root";
 private static final String PASSWORD="12345";
 
 private static DBHelper dbHelper=null;
 private Connection connection=null;
 
 static {
	 try {
		Class.forName(DRIVER);
	} catch (Exception e) {
		e.printStackTrace();
	}
 }
 
 private DBHelper(){
	 try {
		connection=DriverManager.getConnection(URL,USER,PASSWORD);
	} catch (SQLException e) {
		e.printStackTrace();
	}
 }
 
 public static DBHelper getDBHelper(){
	 if(dbHelper==null){
		 dbHelper=new DBHelper();
	 }
	 return dbHelper;
 }
 
 //查询
 public ResultSet executeQuery(String sql) throws Exception{
	 PreparedStatement statement=connection.prepareStatement(sql);
	 return statement.executeQuery(); 
 }
 
 public ResultSet executeQuery(String sql,Object...args)throws Exception{
	 PreparedStatement pstmt =connection.prepareStatement(sql);
	 if(args!=null){
		 for(int i=0;i<args.length;i++){
			 Object arg=args[i];
			 pstmt.setObject(i+1, arg);
		 }
	 }
	 return pstmt.executeQuery();
 }
 //更新
public int executeUpdate(String sql) throws Exception{
	 Statement statement=connection.createStatement();
	 return statement.executeUpdate(sql); 
}

public int executeUpdate(String sql,Object...args)throws Exception{
	 PreparedStatement pstmt =connection.prepareStatement(sql);
	 if(args!=null){
		 for(int i=0;i<args.length;i++){
			 Object arg=args[i];
			 pstmt.setObject(i+1, arg);
		 }
	 }
	 return pstmt.executeUpdate();
}

public void close(){
	try {
		if (connection != null && !connection.isClosed()) {
			connection.close();
		}
	} catch (Exception e) {
		e.printStackTrace();
	} finally {
		connection = null;
		dbHelper = null;
	}
}
}
